﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml;
using System.Xml.Linq;

namespace LotroData
{
    class LotroGuildParser : LotroBaseParser<LotroGuild> 
    {
        public LotroGuildParser()
            : base()
        { }

        public LotroGuildParser(string cachePath)
            : base(cachePath)
        { }

        public LotroGuildParser(bool suppressErrors)
            : base(suppressErrors)
        { }

        public LotroGuildParser(string cachePath, bool suppressErrors)
            : base(cachePath, suppressErrors)
        { }

        protected override LotroGuild ParseXml(XDocument doc, string name, LotroWorld world)
        {
            var guild = new LotroGuild();

            var guildElement = doc.Elements("apiresponse").Elements("guild").Single();

            guild.Name = guildElement.Attribute("name").Value;
            guild.World = (LotroWorld)Enum.Parse(typeof(LotroWorld), guildElement.Attribute("world").Value);
            guild.GuildType = (LotroGuildType)Enum.Parse(typeof(LotroGuildType), guildElement.Attribute("theme").Value.Replace(" ", "_"));
            guild.MemberCount = int.Parse(guildElement.Attribute("memberCount").Value);

            var characters = doc.Elements("apiresponse").Elements("guild").Elements("characters");

            foreach (var character in characters.Elements("character"))
            {
                LotroCharacter charac;
                if (guild.GuildType.ToString().Contains("Kinship"))
                    charac = new LotroFreeCharacter();
                else
                    charac = new LotroMonsterCharacter();

                charac.World = guild.World;
                charac.Name = character.Attribute("name").Value;
                charac.Level = int.Parse(character.Attribute("level").Value);
                charac.Class = (LotroClass)Enum.Parse(typeof(LotroClass), character.Attribute("class").Value.Replace("-", "_"));
                charac.Race = (LotroRace)Enum.Parse(typeof(LotroRace), character.Attribute("race").Value.Replace(" ", "_"));
                charac.GuildRank = (LotroGuildRank)Enum.Parse(typeof(LotroGuildRank), character.Attribute("rank").Value);
                charac.Guild = guild.Name;

                //If the character is not already in the collection.
                if (!guild.Characters.ContainsKey(charac.Name))
                    guild.Characters.Add(charac.Name, charac);
            }

            return guild;
        }
    }
}
